var key	= 'session_id';
var EXPIRES	= 20 * 60 * 1000;
var sessions = {};

var generate = function(){
	var session = {};
	session.id = (new Date()).getTime() + Math.random();
	session.cookie = {
		expire	: (new Date()).getTime() + EXPIRES
	};
	sessions[session.id] = session;
	return session;
}
var session_start	= function(req,res){
	var cookie = req.headers.cookie;
	if(!cookie){
		var id = null;
	}else{
		var cookies = {};
		var list = cookie.split(';');
		for (var i=0;i<list.length;i++){
			var pair = list[i].split('=');
			cookies[pair[0].trim()] = pair[1];
		}
		var id = cookies[key];
	}
	if(!id){
		req.session = generate();
	}else{
		var session = sessions[id];
		if(session) {
			if(session.cookie.expire > (new Date()).getTime()){
				//更新超时时间
				session.cookie.expire = (new Date()).getTime() + EXPIRES;
				req.session = session;
			}
		}else{
			//超时了，删除旧数据
			delete sessions[id];
			req.session = generate();
		}
	}
}
module.exports = session_start;